<template>
  <van-nav-bar title="邮箱认证" left-text="" left-arrow @click-left="goBack" />
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="email" label="邮箱" :model-value="LoginUser.email" readonly/>
      <div class="yzmbox">
        <van-field v-model="yzm" label="验证码" placeholder="请输入验证码"/>
        <van-button type="primary" text="按钮文字" class="btn" @click="start" :disabled="disabled">

          <span v-if="!isSend">{{ buttonText }}</span>
            <van-count-down
              v-else
              ref="countDown"
              millisecond
              :time="time"
              :auto-start="false"
              format="mm分ss秒"
              @finish="onFinish"
              class="countNum"
            />
        </van-button>
      </div>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { ref } from "vue";

const goBack = () => { proxy.$router.go(-1) }
const { proxy } = getCurrentInstance()
const LoginUser = reactive(proxy.$cookies.get("LoginUser"))
const time = ref(60*1000);
const buttonText=ref('发送邮件')
let isSend=ref(false);
let disabled=ref(false);
const yzm=ref('');

let timerId;
// 启用计时器 发送验证码
const start = async ()=>{
  clearInterval(timerId);
  disabled.value=true;
  isSend.value=true;

  let data={
    email:LoginUser.email
  }
  let result=await Api.send(data)
  if (result.code == 1) {
    showSuccessToast({
            message: result.msg
        });
  }

  // 计时器
  timerId = setInterval(() => {
    if (time.value > 0) {
      time.value -= 1000; // 每隔1秒减少1000毫秒
    } else {
      // 时间结束时停止计时器
      stop();
      buttonText.value='重新发送'
      disabled.value=false;
      isSend.value=false;
    }
  }, 1000);
};

// 停止计时器
const stop = () => {
  clearInterval(timerId);
  time.value=60*1000
};

console.log(LoginUser);
// 邮箱验证
const onSubmit = async ()=>{
  const emailCode = yzm.value;
  let data = {
    code: emailCode,
    email: LoginUser.email,
    busid: LoginUser.id
  }
  let result=await Api.email(data)
  if (result.code == 1) {
    showSuccessToast({
            message: result.msg,
            onClose: function() {
                proxy.$router.push('/business/index')
            }
        });
  }
}


</script>

<style scoped>
.yzmbox{
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.btn{
  width: 30%;
}
.countNum{
  color: #fff;
}
</style>>